import re

# 提供规范图片转文字的文件对应的文件名及条目编码列表，输出对应的 对应的内容字符串列表及字典


def gf_tm(file_name, *list_m):
    print("start")
    with open(file_name, 'r', encoding='UTF-8') as f:
        lists = f.readlines()
        f.close()

    i_tem, i_tem2, tem = [], [], []

    # 先把字符串中标题 分标题删除掉（特征 换行符前最后一个字符不是标点符合，一般pdf转word，中间没有换行符，且中间没有标点
    # 好像sublime不能使用(?!),否则搜索起来更方便，python可以

    for j in range(len(lists)):
        lists[j] = re.sub(r"\s+", "", lists[j])
    # [print(i) for i in lists]

    for i in lists:
        if re.search(r"\W$", i) or re.search(r"，|，", i):
            tem.append(i)
        else:
            if i == lists[-1]:
                tem.append(i)
            # else:
            #     print(i)

    lists = tem

    # 随后把条目对应的序号找出来，并把所有空格删除
    for i in range(len(lists)):
        if re.search(r"^(表?)(\d+.)\s?(\d+.)\s?(\d+)", lists[i]):
            fh = re.search(r"^(表?)(\d+.)\s?(\d+.)\s?(\d+)", lists[i]).groups()

            lists[i] = re.sub(r"^(表?)(\d+.)\s?(\d+.)\s?(\d+)",
                              fh[1] + fh[2] + fh[3], lists[i])
            # print(lists[i], "\n", fh)

            i_tem.append(i)

    # 把两个条目中的字符串，放在一个字符串组中，并生成字典。
    list_tem, k_tem = [], []
    dic = {}
    for i in range(len(i_tem)):
        if i < len(i_tem) - 1:
            list_tem.append(lists[i_tem[i]:i_tem[i + 1]])
            s = len(re.search(r"^(\d+.)\s?(\d+.)\s?(\d+)",
                              list_tem[i][0]).group())
            k = list_tem[i][0][:s]
            k_tem.append(k)
            list_tem[i][0] = list_tem[i][0][s:]
            dic[k] = list_tem[i]
        else:
            list_tem.append(lists[i_tem[i]:])
            s = len(re.search(r"^(\d+.)\s?(\d+.)\s?(\d+)",
                              list_tem[i][0]).group())
            k = list_tem[i][0][:s]
            k_tem.append(k)
            list_tem[i][0] = list_tem[i][0][s:]
            dic[k] = list_tem[i]

    # 如果没有第二个参数返回所有规范条文，如果有第二个参数提供需要的条文编号列表，则输出需要的条文
    if not list_m:
        list_mm = list(dic.keys())
    else:
        list_mm = list_m[0]

    # print(list_mm)
    r_d = {}
    r_l = []
    for i in list_mm:
        r_d[i] = dic[i]
        for j in dic[i]:
            r_l.append(j)

    return r_l, r_d


if __name__ == "__main__":
    list_m = ["6.3.5", "6.3.7"]
    r_l, r_d = gf_tm("kzgf.text", list_m)
    # r_l, r_d = gf_tm("djgf.text")
    print(r_d.keys(), r_d.values())
